package cn.hu.org.service.impl;

import cn.hu.basic.constants.Constant;
import cn.hu.basic.service.impl.BaseServiceImpl;
import cn.hu.org.domain.Department;
import cn.hu.org.mapper.DepartmentMapper;
import cn.hu.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService{

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    @CacheEvict(cacheNames = Constant.DEPT_TREE_KEY ,key = "'tree'" )
    public void add(Department department) {
        departmentMapper.add(department);
        this.update(department);
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = Constant.DEPT_TREE_KEY ,key = "'tree'" )
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = Constant.DEPT_TREE_KEY ,key = "'tree'" )
    public void update(Department department) {
        String dirPath = "/";
        //如果父级对象等于null，自己属于顶级部门
        if(department.getParent() == null){
            dirPath = dirPath + department.getId();
        }else{
            //查询父部门
            Department parent = departmentMapper.findById(department.getParent().getId());
            dirPath = parent.getDirPath()+"/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }


    @Override
    @Transactional
    @CacheEvict(cacheNames = Constant.DEPT_TREE_KEY ,key = "'tree'" )
    public void patchDelete(List<Long> ids) {
        departmentMapper.patchDelete(ids);
    }

    @Override
    @Cacheable(cacheNames = Constant.DEPT_TREE_KEY ,key = "'tree'" )
    public List<Department> getDeptTree() {
        return getDeptTreeFromDB();
    }


    private List<Department> getDeptTreeFromDB() {
        List<Department> allDepts = departmentMapper.findAll();
        HashMap<Long, Department> hm = new HashMap<>();
        //结果集
        List<Department> resultDept = new ArrayList<>();
        for (Department dept : allDepts) {
            hm.put(dept.getId(),dept);
        }
        for (Department dept : allDepts) {
            if (dept.getParent_id() == null){
                resultDept.add(dept);
            }else {
                Department parent = hm.get(dept.getParent_id());
                parent.getChildren().add(dept);
            }
        }
        return resultDept;
    }
}
